package com.atguigu.statemachine.config;

import com.atguigu.statemachine.entity.Order;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.support.DefaultStateMachineContext;

import java.util.EnumSet;

/**
 * @author Jungle
 * @create 2025-05-22 8:09
 * @description 配置状态转换事件关系
 */
@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig  extends StateMachineConfigurerAdapter<OrderStatus,OrderEvents> {

    /**
     * 配置状态
     * @param config the {@link StateMachineStateConfigurer}
     * @throws Exception
     */
    @Override
    public void configure(StateMachineStateConfigurer<OrderStatus, OrderEvents> config) throws Exception {
        config.withStates()
                .initial(OrderStatus.INIT)
                .states(EnumSet.allOf(OrderStatus.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<OrderStatus,OrderEvents> transitionConfigurer) throws Exception {
        transitionConfigurer.withExternal().source(OrderStatus.INIT).target(OrderStatus.PAYED)
                .event(OrderEvents.PAY)
                .and()
                .withExternal().source(OrderStatus.PAYED).target(OrderStatus.SHIPPED)
                .event(OrderEvents.SHIPPED)
                .and()
                .withExternal().source(OrderStatus.SHIPPED).target(OrderStatus.RECEIVED)
                .event(OrderEvents.RECEIVE);
    }


    /**
     * 持久化配置
     * 在实际使用中，可以配合Redis等进行持久化操作
     */
    @Bean
    public DefaultStateMachinePersister persister() {
        return new DefaultStateMachinePersister<>(new StateMachinePersist<Object, Object, Order>() {
            @Override
            public void write(StateMachineContext<Object, Object> context, Order order) throws Exception {
                //    此处并没有进行持久化操作
            }

            @Override
            public StateMachineContext<Object, Object> read(Order order) throws Exception {
                // 此处直接获取order中的状态，其实并没有进行持久化读取作
                return new DefaultStateMachineContext<Object, Object>(order.getStatus(), null, null, null);
            }
        });

    }
}
